/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CatalogoUnidadTiempo.java
 *
 * Created on 05-16-2010, 06:43:09 PM
 */
package jepi.ui;

import db.MySQLManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import validadores.api.GrupoValidador;
import validadores.validadoresformato.StringValidador;

/**
 *
 * @author Steve
 */
public class CatalogoUnidadTiempo extends javax.swing.JInternalFrame {

    private final int AGREGAR = 1;
    private final int MODIFICAR = 2;
    private final int ELIMINAR = 3;
    private int accion;
    private int id_seleccionado;
    GrupoValidador validador = new GrupoValidador();

    /** Creates new form CatalogoUnidadTiempo */
    public CatalogoUnidadTiempo() {
        initComponents();
        descripcionValidador.configurarValidacion(descripcionTextField,
                true, "Descripcion no puede quedar vacio",
                new StringValidador("Ingrese la descripcion", 0, "Debe ingresar la descripcion",
                100, "Descripcion no puede tener mas de 50 caracteres"));
        validador.add(descripcionValidador);
        try {
            masterTable.setModelFromSQL("select * from catalogo_unidad_tiempo order by id_unidad_tiempo",
                    new String[]{"Codigo", "Descripcion"});
            masterTable.setAnchoColumna(0, 150);
        } catch (SQLException ex) {
            System.out.println(ex);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToolBar1 = new javax.swing.JToolBar();
        nuevoButton = new javax.swing.JButton();
        modificarButton = new javax.swing.JButton();
        eliminarButton = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        descripcionValidador = new validadores.api.ValidadorJTextComponent();
        descripcionTextField = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        masterTable = new db.TableFromSQL(MySQLManager.getConexionEstatica());
        jPanel2 = new javax.swing.JPanel();
        guardarButton = new javax.swing.JButton();
        cancelarButton = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("Catalogo de Unidades de Tiempo");

        jToolBar1.setRollover(true);

        nuevoButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/create.png"))); // NOI18N
        nuevoButton.setText("Nuevo");
        nuevoButton.setFocusable(false);
        nuevoButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        nuevoButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        nuevoButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nuevoButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(nuevoButton);

        modificarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/modify.png"))); // NOI18N
        modificarButton.setText("Modificar");
        modificarButton.setFocusable(false);
        modificarButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        modificarButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        modificarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                modificarButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(modificarButton);

        eliminarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/delete.png"))); // NOI18N
        eliminarButton.setText("Eliminar");
        eliminarButton.setFocusable(false);
        eliminarButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        eliminarButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        eliminarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                eliminarButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(eliminarButton);

        getContentPane().add(jToolBar1, java.awt.BorderLayout.NORTH);

        descripcionTextField.setEnabled(false);

        jLabel1.setText("Descripcion");

        masterTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null}
            },
            new String [] {
                "Title 1"
            }
        ));
        masterTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_NEXT_COLUMN);
        masterTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                masterTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(masterTable);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(descripcionTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(descripcionValidador, javax.swing.GroupLayout.DEFAULT_SIZE, 255, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 574, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(218, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(descripcionValidador, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(descripcionTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE)
                    .addGap(45, 45, 45)))
        );

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        guardarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/guardar.png"))); // NOI18N
        guardarButton.setText("Guardar");
        guardarButton.setEnabled(false);
        guardarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                guardarButtonActionPerformed(evt);
            }
        });

        cancelarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/cerrar.png"))); // NOI18N
        cancelarButton.setText("Cancelar");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(360, Short.MAX_VALUE)
                .addComponent(guardarButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cancelarButton)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cancelarButton)
                    .addComponent(guardarButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        getContentPane().add(jPanel2, java.awt.BorderLayout.SOUTH);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void nuevoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nuevoButtonActionPerformed
        accion = AGREGAR;
        descripcionTextField.setEnabled(true);
        guardarButton.setEnabled(true);
        descripcionTextField.requestFocus();
    }//GEN-LAST:event_nuevoButtonActionPerformed

    private void modificarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_modificarButtonActionPerformed
        accion = MODIFICAR;
        id_seleccionado = Integer.parseInt(masterTable.getValueAt(masterTable.getSelectedRow(), 0).toString());
        descripcionTextField.setEnabled(true);
        guardarButton.setEnabled(true);        
        descripcionTextField.requestFocus();
    }//GEN-LAST:event_modificarButtonActionPerformed

    private void eliminarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_eliminarButtonActionPerformed
        accion = ELIMINAR;
        id_seleccionado = Integer.parseInt(masterTable.getValueAt(masterTable.getSelectedRow(), 0).toString());
        guardarButtonActionPerformed(null);
    }//GEN-LAST:event_eliminarButtonActionPerformed

    private void guardarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guardarButtonActionPerformed
        if (validador.validar()) {
            switch (accion) {
                case AGREGAR:
                    String insert = "INSERT INTO catalogo_unidad_tiempo "
                            + "(descripcion) values "
                            + "('" + descripcionTextField.getText() + "')";
                    MySQLManager.ejecutarConsultaUpdate(insert);
                    JOptionPane.showMessageDialog(null, "Registro se ingreso correctamente.", "Notificacion", JOptionPane.INFORMATION_MESSAGE);
                    break;
                case MODIFICAR:
                    String update = "UPDATE catalogo_unidad_tiempo "
                            + "set descripcion='" + descripcionTextField.getText() + "' "
                            + "WHERE id_unidad_tiempo=" + id_seleccionado;
                    MySQLManager.ejecutarConsultaUpdate(update);
                    JOptionPane.showMessageDialog(null, "Registro se modifico correctamente.", "Notificacion", JOptionPane.INFORMATION_MESSAGE);
                    break;
                case ELIMINAR:
                    String delete = "DELETE FROM catalogo_unidad_tiempo "
                            + "where id_unidad_tiempo=" + id_seleccionado;
                    int res = JOptionPane.showConfirmDialog(null, "¿Realmente desea eliminar este registro?", "Confirmacion", JOptionPane.YES_NO_OPTION);
                    if (res == JOptionPane.YES_OPTION) {
                        MySQLManager.ejecutarConsultaUpdate(delete);
                        JOptionPane.showMessageDialog(null, "Registro se elimino correctamente.", "Notificacion", JOptionPane.INFORMATION_MESSAGE);
                    }
                    break;
            }
            masterTable.getTableModel().actualizar();
            masterTable.revalidate();
            masterTable.repaint();
            descripcionTextField.setText("");
            descripcionValidador.cambiarEstadoInicial();
            descripcionTextField.setEnabled(false);
        }
    }//GEN-LAST:event_guardarButtonActionPerformed

    private void masterTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_masterTableMouseClicked
        descripcionTextField.setText(masterTable.getValueAt(masterTable.getSelectedRow(), 1).toString());
    }//GEN-LAST:event_masterTableMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelarButton;
    private javax.swing.JTextField descripcionTextField;
    private validadores.api.ValidadorJTextComponent descripcionValidador;
    private javax.swing.JButton eliminarButton;
    private javax.swing.JButton guardarButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar jToolBar1;
    private db.TableFromSQL masterTable;
    private javax.swing.JButton modificarButton;
    private javax.swing.JButton nuevoButton;
    // End of variables declaration//GEN-END:variables
}
